<?php
namespace Home\Controller;
use Think\Controller;
class UserController extends Controller{
    public function _empty(){
        echo '控制器内没有该方法';
    }
    /**
     *login
     */
    public function login(){
        if (!IS_POST) {
            $this->display();
        }
        $user = new \Home\Model\HomeUserModel();
        if (!$user->create()){
            exit ($user->getError());
        }
       if (!($user->check_verify(I('post.code')))){
           $this->error('验证码输入错误');
       }
        $info=$user->checkNamePwd(I('post.user_name'),I('post.pwd'));
        if (!$info){
            $this->error('登录失败');
        }else {
            //将这次登录时间写入数据库
            //作为数据库的上次登录时间
            $user->lastlogin = time();
            if (!($user->where('user_name=' . I('post.user_name'))->save())) {
                show_bug(I('post.'));
            }
            $salt=C('SALT');
            session('user_name', $_POST['user_name']);
            session('ccode', md5($salt . '|||**' . $_POST['user_name']));
            $this->redirect('Index/index');
        }
    }

    /**
     * logout
     */
    public function logout(){
        session_start();
        session(null);
        $this->redirect('login');
    }

    /**
     * regist
     */
    public function register(){
        if(!IS_POST){
            $this->display();
        }
        $user = new \Home\Model\HomeUserModel();
        if (!$user->create()){
            exit($user->getError());
        }
        //检测用户是否存在
        if (!$user->checkReg()) {
            $msg='用户名已存在';
            $this->redirect('Home/User/error',array('msg' => $msg));
        }else {
            $salt=substr(str_shuffle('aljuudJOMG9875nkbtwslncwp'),0,8);
            $pwdd = md5($_POST['pwd'].$salt);
            $user->pwd = $pwdd;
            $user->salt=$salt;
            $add = $user->add();
            if (!$add) {
                show_bug('用户注册失败');
            } else {
                redirect('login');
            }
        }
    }
    /**
     * verifiImg out
     */
    public function verifyImg(){
        ob_clean();
        $verify = new \Think\Verify();
        $config = array(
            'imageH'    =>  43,              
            'imageW'    =>  150,         
            'fontSIze' => 3,
            'length' => 3,
            'useNoise' => false,
            'useImgBg' => true,
        );
        $Verify=new \Think\Verify($config);
        $Verify->entry();
    }

    /**
     * error html
     */
    public function error(){
        $msg=I('get.msg');
        $cart = \Home\Tool\CartTool::getIns();
        $calcCnt=$cart->calcCnt();
        $this->assign('calcCnt',$calcCnt);
        $this->assign('msg',$msg);
        $this->display();
    }
}
